from django.contrib.auth.models import Group
from rest_framework import serializers


from apps.users.models import User


class AdminSerializer(serializers.ModelSerializer):
    """
    管理员序列化器
    """
    class Meta:
        model = User
        # fields = ("id","username","email","mobile")
        fields = "__all__"
        extra_kwargs={
            "password":{
                "write_only":True
            }
        }

    def create(self, validated_data):
        """
        重写create方法,解决密码没有加密 和 is_staff不是true的问题
        :param validated_data:
        :return:
        """
        #　方式一: 获取user
        # user = User.objects.create_user(**validated_data)
        # 方式二:
        user = super().create(validated_data)
        # 添加 is_staff
        user.is_staff=True
        # 密码不是加密的.设置加密
        # 方式二:
        # user.set_password(validated_data.get("password"))
        user.save()
        return user


    # def update(self, instance, validated_data):
    #     """重写update"""

        # 调用父类方法更新数据
        # instance = super().update(instance,validated_data)
        # if validated_data.get("password"):
        #     instance.set_password(validated_data.get("password"))
        #     instance.save()
        # instance = super().update(instance,validated_data)
        # return instance

class GroupSerializer(serializers.ModelSerializer):
    """
    用户组序列化器
    """
    class Meta:
        model = Group
        fields = "__all__"


